import socket
from . import port_name
from . import watcher_schema
from . import message
schema = watcher_schema.schema

class AlreadyOpenedError(Exception):
  """Exception thrown when the watch server is already connected to."""


class ClientLib(object):

  def __init__(self, port):
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.connect( ("localhost", port) )

  def get_affected(self):
    reply = schema.get_affected(self.sock)
    return reply.args[0]

  def ack_affected(self):
    schema.ack_affected(self.sock)

  def lock(self):
    schema.lock(self.sock)

  def unlock(self):
    schema.unlock(self.sock)

  def watch(self, files):
    schema.watch(self.sock, files)

  def unwatch(self, files):
    schema.unwatch(self.sock, files)

  def drop(self, files):
    schema.drop(self.sock, files)

  def __enter__(self):
    try:
      self.lock()
      return self
    except message.IOClosedException as e:
      raise AlreadyOpenedError('Watch server already in use')

  def __exit__(self, type, value, traceback):
    self.unlock()
